<template>
  <div class="cjui-dynamic-form-editor-library">
    <el-scrollbar>
      <el-collapse v-model="activeGrounp">
        <el-collapse-item v-for="(group, i) in groups" :key="i" :title="group.name" :name="group.name">
          <draggable
            item-key="index"
            :list="group.components"
            :sort="false"
            :group="{ name: 'component', pull: 'clone', put: false }"
            :clone="handleCloneComponent"
            :animation="200"
            :force-fallback="true"
            class="components-draggable"
          >
            <template #item="{ element }">
              <div class="components-item">
                <div class="components-item-icon"></div>
                <div class="components-item-title">{{ element.name }}</div>
              </div>
            </template>
          </draggable>
        </el-collapse-item>
      </el-collapse>
    </el-scrollbar>
  </div>
</template>

<script lang="ts" setup>
import _ from 'lodash-es'
import draggable from 'vuedraggable'
import { componentConfigs, PAGE_LIBS, DiyComponent } from './components/index'

defineOptions({
  name: 'CjuiDynamicFormEditorLibrary'
})

const groups = PAGE_LIBS.map(el => ({ ...el, components: el.components.map(compName => componentConfigs[compName]) }))
const activeGrounp = [groups[0].name]

// 克隆组件
const handleCloneComponent = (component: DiyComponent<any>) => {
  const instance = _.cloneDeep(component)
  instance.uid = new Date().getTime()
  return instance
}
</script>

<style lang="scss">
.cjui-dynamic-form-editor-library {
  width: 100%;
  height: 100%;
  overflow: auto;

  .el-scrollbar__view {
    height: unset;
    padding: 0 10px;
  }

  .el-collapse {
    border-top: none;
    border-bottom: none;

    .el-collapse-item__wrap {
      border-bottom: none;
    }

    .el-collapse-item__header {
      background-color: #f7f8f9;
      margin: 10px 0;
      height: 32px;
      line-height: 32px;
      border-bottom: none;
      padding-left: 10px;
    }

    .el-collapse-item__content {
      padding-bottom: 0;
    }
  }

  .components-draggable {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  .components-item {
    display: inline-block;
    width: 100px;
    background-color: #f3f9ff;
    border-radius: 3px;
    border: 1px dashed transparent;
    font-size: 12px;
    text-align: center;
    transition: transform 0ms;
    margin-bottom: 10px;
    user-select: none;
    cursor: move;

    &:hover {
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
    }

    &.disabled {
      background-color: #e4e7ed;
      cursor: not-allowed;
      border-color: transparent;
      color: #999;

      &:hover {
        border-color: transparent;
        color: #999;
      }
    }
  }

  .components-item-title {
    line-height: 32px;
  }
}
</style>
